//222222222
//  NewsContentCell.m
//  WanCaiC8
//
//  Created by tangang on 2018/4/22.
//  Copyright © 2018年 tangang. All rights reserved.
//

#import "NewsContentCell.h"
#import "MSSBrowseNetworkViewController.h"
#import "AdvertisingView.h"

#import <WebKit/WebKit.h>


@interface NewsContentCell ()<WKUIDelegate,WKNavigationDelegate>
@property (nonatomic ,strong) AdvertisingView        *oneAdvertisingView;
@property (nonatomic ,strong) AdvertisingView        *twoAdvertisingView;
@property (nonatomic ,strong) AdvertisingView       *threeAdvertisingView;
@property (nonatomic ,strong) WKWebView *webView;
@property (nonatomic ,strong) MSSBrowseNetworkViewController *bvc;
@property (nonatomic, strong) MSSBrowseModel *browseItem;
@property (nonatomic ,assign) NSInteger     i;


@end

@implementation NewsContentCell{
    QXLable  *labTitle;
    QXLable  *labTime;
    QXLable  *labContent;
//    NSMutableArray *allUrlArray;
    
}


//- (MSSBrowseNetworkViewController *)bvc{
//    if (_bvc == nil) {
//        // 加载网络图片大图地址
//        _bvc = [[MSSBrowseNetworkViewController alloc] initWithBrowseItemArray:@[_browseItem] currentIndex:0];
//
//    }
//    return _bvc;
//}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self=[super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        
        self.i= 0;
        [self.contentView addSubview:self.oneAdvertisingView];
        [self.oneAdvertisingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.equalTo(self.contentView).offset(10);
            make.right.equalTo(self.contentView).offset(-10);
            make.height.mas_equalTo(@0);
        }];
        labTitle=[[QXLable alloc]initWithBFount:25];
        [self.contentView addSubview:labTitle];
        [labTitle mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.oneAdvertisingView.mas_bottom).with.offset(8);
            make.left.equalTo(self.contentView).with.offset(10);
            make.right.equalTo(self.contentView).with.offset(-10);
        }];
        
        labTime=[[QXLable alloc]initWithFount:13];
        [self.contentView addSubview:labTime];
        [labTime mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labTitle);
            make.top.equalTo(labTitle.mas_bottom).with.offset(14);
            make.right.equalTo(self.contentView).with.offset(-10);
        }];
        
        [self.contentView addSubview:self.twoAdvertisingView];
        [self.twoAdvertisingView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.left.equalTo(self.contentView).offset(10);
            make.right.equalTo(self.contentView).offset(-10);
            make.top.equalTo(labTime.mas_bottom).offset(5);
            make.height.mas_equalTo(@0);
        }];
        
        
        
        self.webView = [[WKWebView alloc] initWithFrame:CGRectZero];
        self.webView.scrollView.scrollEnabled= NO;
        self.webView.navigationDelegate = self;
//        [self.webView addObserver:self forKeyPath:@"scrollView.contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
        [self.contentView addSubview:self.webView];
        [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(labTitle);
            make.top.equalTo(self.twoAdvertisingView.mas_bottom).with.offset(8);
            make.right.equalTo(self.contentView);
            make.height.mas_equalTo(0);
//            make.height.mas_equalTo(1500);
//            make.bottom.equalTo(self.contentView);
        }];
        
        labContent=[[QXLable alloc] initTitle];
//        labContent.font = [UIFont systemFontOfSize:17];
//        [labContent use];
//        WS(weakSelf);
//        labContent.selectBlock = ^(NSInteger i, NSAttributedString *attStr) {
//            NSString *str=weakSelf.content.Content;
//            str=[str stringByReplacingOccurrencesOfString:@"</p" withString:@""];
//            str=[str stringByReplacingOccurrencesOfString:@"<br" withString:@""];
//            str=[str stringByReplacingOccurrencesOfString:@"&gt" withString:@""];
//            str=[str stringByReplacingOccurrencesOfString:@"&lt" withString:@""];
//            str=[str stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
//
//            NSArray *cmps = [[str stringByReplacingOccurrencesOfString:@"<img" withString:@""] componentsSeparatedByString:@">"];
//            NSString *content=@"";
//            NSInteger  row=0;
//            for (NSString *strImage in cmps) {
//                if (![strImage containsString:@"<"]) {
//                    row+=1;
//                    content=[NSString stringWithFormat:@"%@%@",content,strImage];
//
//                }
//                if ([strImage containsString:@".jpg"] || [strImage containsString:@".png"]) {
//                    NSRange rang=[content rangeOfString:strImage];
//                    if (NSLocationInRange(i, rang)) {
//                        NSArray *cmpsImage = [[strImage stringByReplacingOccurrencesOfString:@"src=" withString:@""] componentsSeparatedByString:@"\""];
//                        NSString *imageUrl=cmpsImage[1];
//
//                        MSSBrowseModel *browseItem = [[MSSBrowseModel alloc]init];
//                        browseItem.smallImageView = nil;// 小图
//                        browseItem.bigImageUrl =imageUrl;
//                        // 加载网络图片大图地址
//                        MSSBrowseNetworkViewController *bvc = [[MSSBrowseNetworkViewController alloc]initWithBrowseItemArray:@[browseItem] currentIndex:0];
//                        [bvc showBrowseViewController];
//                        break;
//                    }
//                    else{
//                        content =[content stringByReplacingOccurrencesOfString:strImage withString:@" "];
//                    }
//                }else if (weakSelf.content.adModel.Title.length>0){
//                    if ([strImage containsString:weakSelf.content.adModel.Title]) {
//                        NSRange rang=[content rangeOfString:strImage];
//                        rang=NSMakeRange(rang.location, rang.length+row);
//                        if (NSLocationInRange(i, rang)) {
//                            if (![weakSelf.content.adModel.Title containsString:attStr.string]) {
//                                return ;
//                            }
//                            if (weakSelf.content.adModel.TransferUrl.length>0) {
//                                [[UIApplication sharedApplication]openURL:[NSURL URLWithString: weakSelf.content.adModel.TransferUrl]];
//                            }
//                        }
//                    }
//
//                }
//            }
//
//
//
//
//        };
//        [self.contentView addSubview:labContent];
////        labContent.textColor=[UIColor whiteColor];
//        [labContent mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.left.equalTo(labTitle);
//            make.top.equalTo(self.twoAdvertisingView.mas_bottom).with.offset(8);
//            make.right.equalTo(self.contentView).with.offset(-10);
////            make.height.mas_equalTo(1500);
////            make.bottom.equalTo(self.contentView);
//        }];
        
        [self.contentView addSubview:self.threeAdvertisingView];
        [self.threeAdvertisingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.contentView).offset(10);
            make.right.equalTo(self.contentView).offset(-10);
            make.top.equalTo(self.webView.mas_bottom).with.offset(10);
            make.height.mas_equalTo(@0);
            make.bottom.equalTo(self.contentView);
        }];
    }
    return self;
}

- (void)setContent:(NewsContentModel *)content{
    _content=content;
    labTitle.text=content.Title;

    NSArray *str=[content.ReleaseTime componentsSeparatedByString:@"."];
    if (str.count>0) {
        content.ReleaseTime=str[0];
    }
    str=[content.ReleaseTime componentsSeparatedByString:@"+"];
    if (str.count>0) {
        content.ReleaseTime=str[0];
        
    }
#warning ---change---
//    NSDate *date=[TGTools dateFormatter:@"yyyy-MM-dd'T'HH:mm:ss" andString:content.ReleaseTime];
//    labTime.text=[NSString stringWithFormat:@"%@   %@",APP_NAME,[TGTools dateFormatter:@"MM-dd HH:mm" andDate:date]];
    labTime.text=[NSString stringWithFormat:@"%@   %@",NEW_APP_NAME,[[TGToolForDateFormatter shareInstance] userVisibleDateTimeStringForRFC3339DateTimeString:content.ReleaseTime]];
    
    
//    NSMutableString *contentStr =[NSMutableString stringWithFormat:@"%@",_content.Content];
//    NSLog(@"1-->%@",contentStr);
//  
//    contentStr = [contentStr stringByReplacingOccurrencesOfString:@"\"" withString:@"'"].copy;
//    
//    NSLog(@"2-->%@",contentStr);
    
    /***********************************/
//    NSAttributedString * attStr = [[NSAttributedString alloc] initWithData:[_content.Content dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType} documentAttributes:nil error:nil];
//    NSMutableAttributedString *attStr1=[[NSMutableAttributedString alloc]initWithAttributedString:attStr];
//
//
////    NSMutableAttributedString *str22=[NSMutableAttributedString alloc] initWithString:<#(nonnull NSString *)#> attributes:<#(nullable NSDictionary<NSAttributedStringKey,id> *)#>
////    NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
////    paragraphStyle.alignment = labContent.textAlignment;
////    paragraphStyle.lineSpacing = 0;
//
//
//
//    NSRange textRange = NSMakeRange(0, attStr1.length);
////    NSRange textRange = NSMakeRange(0, attStr1.length);
////    [attStr1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:textRange];
//
////  [attStr1 addAttribute:NSForegroundColorAttributeName value:DEFAULTTEXTBLACKCOLOR range:textRange];
//    [attStr1 addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:17] range:textRange];
//
//
//    labContent.attributedText =attStr1.copy;
    
     /***********************************/
    
    
    [self.webView loadHTMLString:_content.Content baseURL:nil];
    
    
    
    
}

- (void)setArr1:(NSMutableArray *)arr1{
    self.oneAdvertisingView.dataArr=arr1;
}

- (void)setArr2:(NSMutableArray *)arr2{
    self.twoAdvertisingView.dataArr=arr2;
}

- (void)setArr3:(NSMutableArray *)arr3{
    self.threeAdvertisingView.dataArr=arr3;
}

- (AdvertisingView *)oneAdvertisingView{
    if (!_oneAdvertisingView) {
        WS(weakSelf);
        _oneAdvertisingView =[[AdvertisingView alloc]init];
        _oneAdvertisingView.noTimel=YES;
        _oneAdvertisingView.changeHeight = ^(float height) {
            [weakSelf.oneAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@(height));
            }];
        };
    }
    return _oneAdvertisingView;
}

- (AdvertisingView *)twoAdvertisingView{
    if (!_twoAdvertisingView) {
        WS(weakSelf);
        _twoAdvertisingView =[[AdvertisingView alloc]init];
        _twoAdvertisingView.noTimel=YES;
        self.twoAdvertisingView.changeHeight = ^(float height) {
            [weakSelf.twoAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@(height));
            }];
        };
        
    }
    return _twoAdvertisingView;
}

- (AdvertisingView *)threeAdvertisingView{
    if (!_threeAdvertisingView) {
        WS(weakSelf);
        _threeAdvertisingView =[[AdvertisingView alloc]init];
        _threeAdvertisingView.noTimel=YES;
        _threeAdvertisingView.changeHeight = ^(float height) {
            [weakSelf.threeAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@(height));
            }];
        };
        
    }
    return _threeAdvertisingView;
}


- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{

//     [self.webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
    
    NSLog(@"加载完成");
    self.i++;
    
    WS(weakSelf);
    
    
    //这个方法也可以计算出webView滚动视图滚动的高度
//    [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//         NSLog(@"scrollWidth宽度：%.2f",[result floatValue]);
//    }];
    //这个方法也可以计算出webView滚动视图滚动的高度
    [webView evaluateJavaScript:@"document.body.scrollWidth"completionHandler:^(id _Nullable result,NSError * _Nullable error){

        NSLog(@"scrollWidth高度：%.2f",[result floatValue]);
        CGFloat ratio =  CGRectGetWidth(self.webView.frame) /[result floatValue];

        [webView evaluateJavaScript:@"document.body.scrollHeight"completionHandler:^(id _Nullable result,NSError * _Nullable error){
            NSLog(@"scrollHeight高度：%.2f",[result floatValue]);
            NSLog(@"scrollHeight计算高度：%.2f",[result floatValue]*ratio);
            CGFloat newHeight = [result floatValue]*ratio;
            
            if (self.i==1) {
            
//                [weakSelf.webView mas_updateConstraints:^(MASConstraintMaker *make) {
//                    make.height.mas_equalTo(real_size(newHeight));
//                }];
                
                [self.webView mas_remakeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(labTitle);
                    make.top.equalTo(self.twoAdvertisingView.mas_bottom).with.offset(8);
                    make.right.equalTo(self.contentView);
                    make.height.mas_equalTo(newHeight);
                    //            make.height.mas_equalTo(1500);
                    //            make.bottom.equalTo(self.contentView);
                }];
             
                [weakSelf.webView layoutIfNeeded];
                [[NSNotificationCenter defaultCenter] postNotificationName:@"TG_ReloadData" object:nil];
            }
            
//            [ weakSelf.webView evaluateJavaScript:
//             @"var script = document.createElement('script');"
////             "document.body.style.fontSize=0;"//设置字体大小
////             "script.type = 'text/javascript';"
//             "script.text = \"function ResizeImages() { "
//             "var myimg,oldwidth;"
//             "var maxwidth = window.innerWidth;" // UIWebView中显示的图片宽度
//             "for(i=1;i <document.images.length;i++){"
//             "myimg = document.images[i];"
//             "oldwidth = myimg.width;"
//             "myimg.width = maxwidth;"
//             "}"
//             "}\";"
//             "document.getElementsByTagName('head')[0].appendChild(script);ResizeImages();" completionHandler:nil];
            
//            [weakSelf.webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
//            [weakSelf.webView evaluateJavaScript:@"document.activeElement.blur();" completionHandler:nil];
            
            // 禁止放大缩小
            NSString *injectionJSString = @"var script = document.createElement('meta');"
            "script.name = 'viewport';"
            "script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
            "document.getElementsByTagName('head')[0].appendChild(script);";
            [webView evaluateJavaScript:injectionJSString completionHandler:nil];
////            ////     适当增大字体大小
//            [weakSelf.webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '260%'" completionHandler:nil];
//////
//            [weakSelf.webView evaluateJavaScript:@"document.getElementsByTagName('img');for(var i=0;i++){var img = objs[i];img.style.width = '200%';img.style.height='200%'" completionHandler:nil];
            
            
            
            //z注入js
            //MARK:获取图片            
//            static  NSString * const jsGetImages =
//            @"function getImages(){\
//            var objs = document.getElementsByTagName(\"img\");\
//            var imgScr = '';\
//            for(let i=0;i<objs.length;i++){\
//            imgScr = imgScr + objs[i].src +'LQXindex'+ i +'L+Q+X';\
//            objs[i].onclick=function(){\
//            document.location=\"myweb:imageClick:\"+this.src + 'LQXindex' + i;\
//            };\
//            };\
//            return imgScr;\
//            };";
//
//            [webView evaluateJavaScript:jsGetImages completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//
//            }];
//            [webView evaluateJavaScript:@"getImages()" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
////                NSString *urlResurlt = result;
////                allUrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"L+Q+X"]];
////                if (allUrlArray.count >= 2) {
////                    [allUrlArray removeLastObject];// 此时数组为每一个图片的url
////                }
//            }];

        }];
        
       
        
        

    }];

    
    
   
}





- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
//    if (_browseItem == nil) {
//        NSString *str=self.content.Content;
//        str=[str stringByReplacingOccurrencesOfString:@"</p" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"<br" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&gt" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&lt" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
//
//        NSArray *cmps = [[str stringByReplacingOccurrencesOfString:@"<img" withString:@""] componentsSeparatedByString:@">"];
//        NSString *content=@"";
//        NSInteger  row=0;
//        for (NSString *strImage in cmps) {
//            if (![strImage containsString:@"<"]) {
//                row+=1;
//                content=[NSString stringWithFormat:@"%@%@",content,strImage];
//            }
//            if ([strImage containsString:@".jpg"] || [strImage containsString:@".png"]) {
//                NSArray *cmpsImage = [[strImage stringByReplacingOccurrencesOfString:@"src=" withString:@""] componentsSeparatedByString:@"\""];
//                NSString *imageUrl=cmpsImage[1];
//
//                _browseItem = [[MSSBrowseModel alloc]init];
//                _browseItem.smallImageView = nil;// 小图
//                _browseItem.bigImageUrl =imageUrl;
//            }
//        }
//    }
//
    NSString *requestString = [[navigationAction.request URL] absoluteString];
////    if ([requestString containsString:@"myweb:imageClick:"] == NO) {
//////        decisionHandler(WKNavigationActionPolicyAllow);
//////        return;
////    }

    //hasPrefix 判断创建的字符串内容是否以pic:字符开始
    if ([requestString hasPrefix:@"myweb:imageClick:"]) {
        NSString *imageUrl = [requestString substringFromIndex:@"myweb:imageClick:".length];
        [self.bvc showBrowseViewController];
//        decisionHandler(WKNavigationActionPolicyCancel);
//        return;

        
        
    }
    
    
//        NSString *str=self.content.Content;
//        str=[str stringByReplacingOccurrencesOfString:@"</p" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"<br" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&gt" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&lt" withString:@""];
//        str=[str stringByReplacingOccurrencesOfString:@"&nbsp" withString:@" "];
//
//        NSArray *cmps = [[str stringByReplacingOccurrencesOfString:@"<img" withString:@""] componentsSeparatedByString:@">"];
//        NSString *content=@"";
//        NSInteger  row=0;
//        for (NSString *strImage in cmps) {
//            if (![strImage containsString:@"<"]) {
//                row+=1;
//                content=[NSString stringWithFormat:@"%@%@",content,strImage];
//
//            }
//            if ([strImage containsString:@".jpg"] || [strImage containsString:@".png"]) {
//                    NSArray *cmpsImage = [[strImage stringByReplacingOccurrencesOfString:@"src=" withString:@""] componentsSeparatedByString:@"\""];
//                    NSString *imageUrl=cmpsImage[1];
//
//                    MSSBrowseModel *browseItem = [[MSSBrowseModel alloc]init];
//                    browseItem.smallImageView = nil;// 小图
//                    browseItem.bigImageUrl =imageUrl;
//                    // 加载网络图片大图地址
//                    MSSBrowseNetworkViewController *bvc = [[MSSBrowseNetworkViewController alloc]initWithBrowseItemArray:@[browseItem] currentIndex:0];
//                    [bvc showBrowseViewController];
//                    break;
//                }
//                else{
//                    content =[content stringByReplacingOccurrencesOfString:strImage withString:@" "];
//                }
         
//        }


    decisionHandler(WKNavigationActionPolicyAllow);
    //允许webView的点击时数据的获取
}


@end
